﻿using elasticsearchDemo.Comm;
using elasticsearchDemo.Model;
using Microsoft.AspNetCore.Mvc;
using Nest;
using System.Collections.Generic;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace elasticsearchDemo.Controllers
{
    [Route("/api")]
    [ApiController]
    public class ESController : ControllerBase
    {
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="param"></param>
        [HttpPost("IndexAsync")]
        public async Task<dynamic> IndexAsync([FromBody] Product param)
        {
            var response = ElasticSearchConnection._esClient.Index(param, x => x.Index("producttest"));
            //var response = ElasticSearchConnection._esClient.Create(param, a => a.Index("producttest"));
            return response.IsValid ? Ok(response.Id) : StatusCode(500);
        }
        /// <summary>
        /// 查询单个
        /// </summary>
        /// <param name="param"></param>
        [HttpGet("GetAsync")]
        public async Task<dynamic> GetAsync(string id)
        {
            var response = ElasticSearchConnection._esClient.GetAsync<Product>(id, x => x.Index("producttest"));
            return response.Result.IsValid ? Ok(response.Result.Source) : NotFound();
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        [HttpPut("UpdateAsync")]
        public async Task<dynamic> UpdateAsync(string id, [FromBody] Product value)
        {
            var response = await ElasticSearchConnection._esClient.UpdateAsync<Product>(id, x => x.Index("producttest").Doc(value));
            return response.IsValid ? Ok(response.Id) : StatusCode(500);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("DeleteAsync")]
        public async Task<dynamic> DeleteAsync(string id)
        {
            var response = await ElasticSearchConnection._esClient.DeleteAsync<Product>(id, x => x.Index("producttest"));
            return response.IsValid;
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="param"></param>
        [HttpPost("SearchAsync")]
        public async Task<dynamic> SearchAsync(string keyword,int From, int Size)
        {
            var request = new SearchRequest
            {
                From = From,
                Size = Size,
                Query = new MatchQuery { Field = "name", Query = keyword } //||
                        //new MatchQuery { Field = "content", Query = keyword }
            };
            var response = await ElasticSearchConnection._esClient.SearchAsync<Product>(request);
            return Ok(response.Documents);
        }
      
        /// <summary>
        /// 查询单个
        /// </summary>
        /// <param name="param"></param>
        [HttpGet("Mapping")]
        public async Task<dynamic> Mapping()
        {
            var response1 = ElasticSearchConnection._esClient.IndexDocument("producttest");
            var response = ElasticSearchConnection._esClient.Map<Product>(m => m.Properties(p => p.Text(t => t.Name("timestamp"))).AutoMap());
            return response.IsValid ? Ok() : NotFound();
        }
        /// <summary>
        /// 第一次分页查询
        /// </summary>
        /// <param name="param"></param>
        [HttpPost("FirstSearchAsync")]
        public async Task<dynamic> FirstSearchAsync()
        {
            var from = 0;
            var size = 20;
            var response = await ElasticSearchConnection._esClient.SearchAsync<Product>(s => s
               
                .From(from)
                .Size(size)
                .Index("producttest")
                .Sort(ss => ss
                    .Descending(f => f.Timestamp)
                ).Pretty()
            );

            return Ok(response.Documents);
        }
        /// <summary>
        /// 深分页查询 根据上一页的id和时间戳来查询下也要
        /// </summary>
        /// <param name="param"></param>
        [HttpPost("keywordSearchAsync")]
        public dynamic keywordSearchAsync( int Size,  long timestamp)//string keyword,
        {
            //var mustQuerys = new List<Func<QueryContainerDescriptor<Product>, QueryContainer>>();
            //if (!string.IsNullOrEmpty(keyword))
            //    mustQuerys.Add(a => a.Term(t => t.Field(f => f.Name).Value(keyword)));
            var response = ElasticSearchConnection._esClient.Search<Product>(a =>
               a.Index("producttest")
                   .Size(Size)
                   //.Query(q => q.Bool(b => b.Must(mustQuerys)))
                   .SearchAfter(timestamp)
                   .Sort(s => s.Field(f => f.Timestamp, SortOrder.Descending)));
            return Ok(response.Documents);
        }
        /// <summary>
        /// 深分页查询 根据上一页的id和时间戳来查询下也要
        /// </summary>
        /// <param name="param"></param>
        [HttpPost("SSearchAsync")]
        public async Task<dynamic> SSearchAsync(int Size, string id, long timestamp)
        {
            var sorts = new List<ISort>();
            sorts.Add(new FieldSort { Field = Infer.Field<Product>(p => p.Timestamp), Order = SortOrder.Descending });

            var searchRequest = new SearchRequest<Product>()
            {
               
                Size = Size,
                Version = true,
                Sort = sorts
            };
            
            var searchResponse = await ElasticSearchConnection._esClient.SearchAsync<Product>(searchRequest);
            return Ok(searchResponse.Documents);
        }
    }

}
